﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using MSRoomLocator.Models;
using MSRoomLocator.ViewModels;
using System.Xml.Linq;
using System.IO;
using System.Linq;


namespace MSRoomLocator
{
    public class MainViewModel : INotifyPropertyChanged
    {
        
        public string Theme = "Dark";

        public MainViewModel()
        {           
            ViewPort = new ViewPort() { ScreenX = 0, ScreenY = 150, ScreenWidth = 750, ScreenHeight = 400 };
        }

        /// <summary>
        /// A collection for ItemViewModel objects.
        /// </summary>
        public ObservableCollection<BuildingViewModel> Buildings { get; private set; }

        private BuildingViewModel _selectedBuilding;
        /// <summary>
        /// Sample ViewModel property; this property is used in the view to display its value using a Binding
        /// </summary>
        /// <returns></returns>
        public BuildingViewModel SelectedBuilding
        {
            get
            {
                return _selectedBuilding;
            }
            set
            {
                if (value != _selectedBuilding)
                {
                    _selectedBuilding = value;
                    NotifyPropertyChanged("SelectedBuilding");
                }
            }
        }

        private RoomViewModel _goalRoom;
        public RoomViewModel GoalRoom
        {
            get
            {
                return _goalRoom;
            }
            set
            {
                if (value != _goalRoom)
                {
                    _goalRoom = value;
                    NotifyPropertyChanged("GoalRoom");
                }
            }
       
        }

        private RoomViewModel _startRoom;
        /// <summary>
        /// Sample ViewModel property; this property is used in the view to display its value using a Binding
        /// </summary>
        /// <returns></returns>
        public RoomViewModel StartRoom
        {
            get
            {
                return _startRoom;
            }
            set
            {
                if (value != _startRoom)
                {
                    _startRoom = value;
                    NotifyPropertyChanged("StartRoom");
                }
            }
        }

        public bool IsDataLoaded
        {
            get;
            private set;
        }

        public ViewPort ViewPort;

        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        public void LoadData()
        {
            Buildings = new ObservableCollection<BuildingViewModel>();
            XDocument xdoc = XDocument.Load("Content/Buildings.xml");
            foreach (var b in xdoc.Descendants("Building"))
            {
                Buildings.Add(
                    new BuildingViewModel
                    {
                        Name = b.Attribute("Name").Value,
                        Floors = int.Parse(b.Attribute("Floors").Value),
                        Latitude = double.Parse(b.Attribute("Latitude").Value),
                        Longitude = double.Parse(b.Attribute("Longitude").Value),
                        TopLeftLatitude = double.Parse(b.Attribute("TopLeftLatitude").Value),
                        TopLeftLongitude = double.Parse(b.Attribute("TopLeftLongitude").Value),
                        BottomRightLatitude = double.Parse(b.Attribute("BottomRightLatitude").Value),
                        BottomRightLongitude = double.Parse(b.Attribute("BottomRightLongitude").Value)
                    });
            }

            this.IsDataLoaded = true;
        }

        // return all conf rooms of selected building
        public List<RoomViewModel> GetRooms()
        {
            ObservableCollection<RoomViewModel> rooms = new ObservableCollection<RoomViewModel>();
            for (int i = 1; i <= this.SelectedBuilding.Floors; i++)
            {
                string floorplanFileName = string.Format("Content/PlanPath/{0}f{1}.xml", App.ViewModel.SelectedBuilding.Name, i.ToString());
                XDocument xdoc = XDocument.Load(floorplanFileName);
                var group = from g in xdoc.Descendants(XName.Get("g", "http://www.w3.org/2000/svg"))
                            where g.Attribute("id").Value == "rooms"
                            select g;

                foreach (var p in group.Descendants(XName.Get("path", "http://www.w3.org/2000/svg")))
                {
                    if (p.Attribute("desc").Value == "Conference")
                    {
                        rooms.Add(new RoomViewModel()
                        {
                            ID = p.Attribute("id").Value,
                            Building = App.ViewModel.SelectedBuilding.Name,
                            Floor = i,
                            Name = string.Format("{0} {1}/{2}", p.Attribute("desc").Value, App.ViewModel.SelectedBuilding.Name, p.Attribute("id").Value)
                        });
                    }
                }
            }

            List<RoomViewModel> roomsList = rooms.ToList();
            roomsList.Sort(delegate(RoomViewModel r1, RoomViewModel r2) { return r1.ID.CompareTo(r2.ID); });
            return roomsList;
        }

        public RoomViewModel GetRoom(string roomName)
        {
            string floorplanFileName = string.Format("Content/PlanPath/{0}f{1}.xml", App.ViewModel.SelectedBuilding.Name, App.ViewModel.GoalRoom.Floor.ToString());
            XDocument xdoc = XDocument.Load(floorplanFileName);
            var roomGroup = from g in xdoc.Descendants(XName.Get("g", "http://www.w3.org/2000/svg"))
                            where g.Attribute("id").Value == "rooms"
                            select g;

            var room =  (
                        from r in roomGroup.Descendants(XName.Get("path", "http://www.w3.org/2000/svg"))
                        where r.Attribute("id").Value == roomName
                        select r
                        ).FirstOrDefault();
            
            return room == null ? null : 
                new RoomViewModel()
                    {
                        ID = room.Attribute("id").Value,
                        Building = App.ViewModel.SelectedBuilding.Name,
                        Floor = App.ViewModel.GoalRoom.Floor, // 楼层和目标房间楼层一致
                        Name = string.Format("{0} {1}/{2}", room.Attribute("desc").Value, App.ViewModel.SelectedBuilding.Name, room.Attribute("id").Value)
                    };
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}